package com.xb.p26_bindservice;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    final static String LOG_TAG="MainActivity";
    MyBindService mService;
    private boolean flag=false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.bindService).setOnClickListener(new MyClick());
        findViewById(R.id.bindCancel).setOnClickListener(new MyClick());
        findViewById(R.id.getRandom).setOnClickListener(new MyClick());
    }


    ServiceConnection mConnection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(LOG_TAG,"onServiceConnected");
            MyBindService.MyBind myBind= (MyBindService.MyBind) service;
            mService=myBind.getService();
            flag=true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(LOG_TAG,"onServiceDisconnected");
            flag=false;
        }
    };


    class MyClick implements View.OnClickListener{
        Intent intent=new Intent(MainActivity.this,MyBindService.class);
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.bindService:
                    bindService(intent,mConnection, Context.BIND_AUTO_CREATE);
                    break;
                case R.id.bindCancel:
                    if(flag){
                        unbindService(mConnection);
                        flag=false;
                    }

                    break;
                case R.id.getRandom:
                    if (flag){
                        Toast.makeText(MainActivity.this, "从服务中获取到的随机数为："+mService.getRandomNum(), Toast.LENGTH_LONG).show();
                    }else{
                        Toast.makeText(MainActivity.this, "没有绑定服务", Toast.LENGTH_LONG).show();
                    }
                    break;
            }
        }
    }
}